<?php


namespace App\Http\Controllers\Order;

use App\Http\Controllers\Controller;
use App\Models\Business\Business;
use App\Models\Order\BusinessCart;
use http\Env\Response;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Validator;
use Illuminate\Support\Facades\DB;

/**
 * @group 商家购物车接口
 *
 * 采用 restful api
 *
 * Body Parameters 表示请求的所需要的参数
 *
 * Query Parameters 表示返回参数的名称
 */
class BusinessCartController extends Controller
{
    /**
     * 商家购物车 用户查看所有购物车情况
     *
     * 200查询成功
     *
     * @queryParam num 购买商品数量
     * @queryParam food->name 商品名
     * @queryParam food->price 价格
     * @queryParam food->food_num 库存
     * @queryParam id 购物车id号
     */

    public function index(Request $request){

        //数据验证
        $validator = Validator::make($request->all(),genValidate());
        if($validator->fails()){
            return response()->json(encodeMsg($validator->errors()->messages(),400),400);
        }
        $userId = $request->user_id;
        $query = BusinessCart::with('food')->where('business_id','=',$userId);
        $data = $query->get()->toArray();
        $total_price = 0;
        foreach ($data as $value)
        {
            $total_price += $value['num'] * $value['food']['price'];
        }
        $total_price = round($total_price,2);
        $res = ['data'=>$data,'price'=>$total_price];
        return response()->json($res,200);
    }
    /**
     * 商家的所有购物车 用户获取在特定商家中的所有购物车信息 url后的id表示购物车id
     * 商家的id号和获取商家信息中使用的id号一致
     *
     * 权限问题
     * 只有user_type为1的可以使用该接口
     * 用户本人通过会话获取本人的购物车 无法获取他人的购物车
     *
     * 200 查询成功
     * 414 没有该购物车数据
     *
     * @queryParam num 购买商品数量
     * @queryParam food->name 商品名
     * @queryParam food->price 价格
     * @queryParam food->food_num 库存
     *
     */
    public function show(Request $request,$pk){

        $userId = $request->user_id;
        $query = BusinessCart::with('food')->where('business_id','=',$userId);
        $data = $query->get()->toArray();
        if($data === [])
            return response()->json('没有数据',414);
        $price = 0;
        foreach ($data as $d)
        {
            $price += $d['num'] * $d['food']['price'];
        }
        $price = round($price,2);
        $res = ['data'=>$data,'price'=>$price];
        return response()->json($res,200);
    }
    /**
     * 商家添加或者修改购物车数量
     * 向用户的购物车中新增商品的功能
     * 前端逻辑
     * 提交商品id号和商品的数量
     * 需要先登录
     * 返回成功的商品数量 商品id 和用户id
     *
     * 权限问题
     * 只有user_type为1的可以使用该接口
     *
     * 200 添加成功
     * 400 请求参数错误
     * 414 服务器错误 添加失败
     *
     * @bodyParam food int required 商品货号
     * @bodyParam num int required 商品数量
     */

    public function store(Request $request)
    {
        //数据验证
        $validator = Validator::make($request->all(),genValidate());
        if($validator->fails()){
            return response()->json(encodeMsg($validator->errors()->messages(),400),400);
        }
        $userId = $request->user_id;
        $foodId = $request->get('food');
        $num = $request->get('num');

        DB::beginTransaction();
        $record = BusinessCart::where(['good_id'=>$foodId,'business_id'=>$userId])->first();
        if($record != []){
            try {
                if ($request->get('num') == 0){
                    $res = BusinessCart::where('id',$record['id'])->delete();
                }else{
                    $record->num = $request->get('num');
                    $record->save();
                    $res = $record;
                }

            }catch (\Exception $e)
            {
                DB::rollback();
                $res = false;
            }
        }else{
            try {
                $res = BusinessCart::create(['good_id' => $foodId, "business_id" => $userId, 'num' => $num]);
            }catch (\Exception $e)
            {
                dd($e->getMessage());
                DB::rollback();
                $res = false;
            }
        }
        DB::commit();
        if($res === false)
        {
            dd($res);
            return response()->json('添加失败服务器错误',414);
        }else{
            return response()->json($res,200);
        }
    }
    /**
     * 用户删除购物车 这里是一条一条的删除
     *
     * 414 没有这个购物车信息 无法删除
     * 200 成功删除
     */
    public function destroy(Request $request,$pk)
    {
        $data = BusinessCart::where(['business_id'=>$request->user_id,'id'=>$pk]);
        if($data === [])
            return response()->json('无该购物车信息',414);
        $data->delete();
        return response()->json('删除成功',200);

    }
    /**
     * 用户删除全部购物车
     *
     * @bodyParam business json required id号  [1,2,3]
     *
     * 414 没有这个购物车信息 无法删除
     * 200 成功删除
     */
    public function alldelete(Request $request)
    {
        if ($request->has('business')){
                $row=json_decode($request->get('business'));
                foreach ($row as $k =>$v){
                    $data = BusinessCart::where(['id'=>$v])->first();
                    if($data == []){
                        return response()->json('无该购物车信息',404);
                    }
                    BusinessCart::where(['id'=>$v])->delete();
                }
        }
        return response()->json('删除成功',200);

    }

}